import config from '../../common/config.js';

export default {
    REQUEST_URL_PREFIX : 'http://miraclegenesis.cn',
    CURRENT_BOX_INDEX : null,
    ERROR_CALLBACK : [],
    globalError : true,
    error(callback){
        this.ERROR_CALLBACK.push(callback);
    },
    request(interfaceURL, options){
        let self = this;
        options = Object.assign({}, {
            type : 'GET',
            data : null,
			headers : {},
            dataType : 'json',
            success : function () {

            },
            fail : function(){

            },
            error : function () {

            },
        }, options);

        return uni.request({
            url : this.REQUEST_URL_PREFIX + interfaceURL,
            method : options.type,
            header : options.headers,
            dataType : options.dataType,
            data : options.data,
            success : function (data) {
				let newData = data['data'];
				let dataType = options.dataType.toLowerCase();
				
				if(typeof data['data'] === 'string'){
					if(dataType === 'jsonp'){
						newData = newData.replace(/^\(/, '').replace(/\)$/, '');
						try{
							newData = JSON.parse(newData);
						}catch(e){
							return options.fail(data['data']);
						}
						if(newData['State']){
							if(parseInt(newData['State']) === 0){
								options.success(newData);
							}else{
								options.fail(newData);
							}
						}else{
							options.success(newData);
						}
					}
					return;
				}
				
				if(parseInt(data['data']['State']) === 0){
					options.success(data['data']);
				}else{
					options.fail(data['data']);
				}
            },
            fail : function (data) {
                if(self.globalError){
                    for (let i = 0; i < self.ERROR_CALLBACK.length; i++){
                        let result = self.ERROR_CALLBACK[i](data);
                        if(result === false)
                            break;
                    }
                }
                options.error(data);
            }
        });
    },
	setUserInfo(data){
		uni.setStorageSync('userInfo', JSON.stringify(data));
	},
	getUserInfo(){
		let userInfo = uni.getStorageSync('userInfo') || '{}';
		return JSON.parse(userInfo);
	},
};